<template>
  <van-row style="padding: 16px 20px;">
    <van-col span="4" style="display: flex; align-items: center;">
      <router-link to="javascript:void(0)" class="back-button" @click="$router.go(-1)">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M15.41 7.41L14 6L8 12L14 18L15.41 16.59L10.83 12L15.41 7.41Z" fill="#000000"/>
        </svg>
      </router-link>
    </van-col>

    <van-col span="16">
      <span style="font-size: 18px; font-weight: bold; display: block; text-align: center;">内容详情</span>
    </van-col>
  </van-row>
  <div class="container">
    <div class="card">
      <h1 class="card__title">{{ data.title}}</h1>
      <div class="card__author">
        <img v-if="author.imageUrl" :src="author.imageUrl" alt="Author Avatar" class="card__avatar">
        <span v-if="author.username">作者: {{ author.username }}</span>
        <span v-else>作者信息加载中...</span>

        <p class="card__date">{{ data.createdAt }}</p>
      </div>
      <div v-html="data.content" class="card__content"></div>
      <div class="card__images">
        <img v-for="(file, index) in data.files" :key="index" :src="file.fileUrl" alt="Article Image"
             class="card__image">
      </div>
      <div class="card__count">
        <span>
          <button  @click="handleGoods(articleId)"> <van-icon name="good-job-o" /> {{ data.goods }}</button></span>
        <span><van-icon name="eye-o" /> {{ data.views }}</span>
        <span>
          <!-- 定义弹框内容 -->
   <van-icon name="comment-o" @click="openDialog" />
    <van-dialog v-model:show="dialogVisible" title="评论内容" show-cancel-button>
    <van-cell-group inset>
      <van-field
          v-model="comment"
          rows="2"
          autosize
          label="留言"
          type="textarea"
          maxlength="50"
          placeholder="请输入留言"
          show-word-limit
      />
    </van-cell-group>
    <template #footer>
      <van-button @click="closeDialog">取消</van-button>
      <van-button type="primary" @click="submitComment">确认</van-button>
    </template>
  </van-dialog> {{ data.commentsCount }}</span>
        <div>
          <button class="icon-button" @click="navigateToComplaint">
            <van-icon name="ellipsis" />
          </button>
        </div>
      </div>
    </div>
  </div>
  <!-- 在原有模板的基础上新增以下代码 -->
  <div class="card__comments">
    <h2 class="card__comments-title">评论区</h2>
    <ul class="card__comments-list">
      <li v-for="(comment, index) in comments" :key="index" class="card__comment-item">
        <div class="comment-info">
          <img v-if="comment.authorImageUrl" :src="comment.authorImageUrl" alt="Author Avatar" class="card__avatar">
          <span v-if="comment.authorUsername" class="author-name">{{ comment.authorUsername }}</span>
        </div>
        <p class="card__comment-content">{{ comment.content }}</p>
      </li>
    </ul>
  </div>

</template>

<script>
import {get, post} from "../../util/request.js";

export default {
  props: ['articleId'], // 接收路由参数 id 作为 props

  data() {
    return {
      data: null, // 初始化为null，等待数据加载
      author: {}, // 作者信息初始化
      author1:{},
      dialogVisible: false,
      comment: '',
      comments: [],
      comment1:'',
    };
  },
  methods: {
    navigateToComplaint() {
      // 确保 articleId 已经定义并且有值
      if (this.articleId) {
        this.$router.push({ name: 'complaint', params: { articleId: this.articleId } });
      } else {
        console.warn('articleId is not defined.');
        // 可能需要处理articleId缺失的情况
      }
    },
    openDialog() {
      this.dialogVisible = true;
      console.log('打开对话框');
    },
    closeDialog() {
      this.dialogVisible = false;
      this.comment = '';

    },
    async fetchComments() {
      try {
        const response = await get(`study/review/findAll/${this.articleId}`, {
          // 假设需要传递文章ID来获取特定文章的评论，根据实际情况调整
        });

        if (response.data.code === 0) {
          this.comments = response.data.data;   // 假定返回的数据直接是评论数组
          //遍历返回得到的评论数组
          for (let i = 0; i < this.comments.length; i++) {
            const comment = this.comments[i];
            const response = await get(`user/user/selectUser/${comment.userId}`);
            if (response.code === 0) {
              const userData = response.data;
              comment.authorUsername = userData.username;
              comment.authorImageUrl = userData.imageUrl;
              console.log(comment);
           } else {
           }
         }
        } else {
          console.error('Failed to fetch comments', response.data.msg);
        }
      } catch (error) {
        console.error('Error fetching comments', error);
      }
    },
    async submitComment() {
      try {
        const response = await post(`study/review/comment?articleId=${this.articleId}&comment=${this.comment}` );
        const commentsCount = await this.fetchCommentCount(this.articleId);
        this.data.commentsCount = commentsCount;
        console.log('评论提交成功', response.data);
        this.closeDialog(); // 提交成功后关闭对话框
        //调用方法增加评论数量
        this.comment = ''; // 清空评论内容
        this.$toast.success('评论提交成功');
        //局部刷新评论区
      } catch (error) {
        console.error('提交评论失败', error);
        this.$toast.fail('评论提交失败');
      }
    },
    async handleGoods(articleId) {
      try {
        const response = await post(`study/article/goods/${articleId}`);
        if (response.data.code === 0) {
          alert('点赞成功');
          // 获取最新的点赞数
          const likesCount = await this.fetchLikesCount(articleId);
          // 更新组件中的点赞数
          this.data.goods = likesCount;
        } else {
          alert('点赞失败');
        }
      } catch (error) {
        console.error('点赞请求异常：', error);
      }
    },

    async fetchLikesCount(articleId) {
      try {
        const response = await get(`study/article/goods/${articleId}/goods`);
        const goods = response.data.data.goods;
        return goods;// 假设后端返回的数据结构中有一个字段叫做 likes
      } catch (error) {
        console.error('获取点赞数异常：', error);
        return 0; // 出错时返回默认值
      }
    },
    async fetchCommentCount(articleId) {
      try {
        const response = await get(`study/article/commentsCount/${articleId}/commentsCount`);
        const commentsCount = response.data.data.commentsCount;
        return commentsCount;// 假设后端返回的数据结构中有一个字段叫做 likes
      } catch (error) {
        console.error('获取点赞数异常：', error);
        return 0; // 出错时返回默认值
      }
    }
  },
    async created() {
    await this.fetchComments();
    //当进入详情页面增加阅读数
    const response = await get(`study/article/addViews/${this.articleId}`);
    try {
      // 获取文章详情
      const articleResponse = await get(`study/article/selectByArticleId/${this.articleId}`);
      if (articleResponse.data.code === 0) {
        this.data = articleResponse.data.data;

        // 假设userId在data中
        const userId = this.data.userId;

        // 获取用户信息
        const userResponse = await get(`user/user/selectUser/${userId}`);
        if (userResponse.code === 0) {
          this.author = {
            username: userResponse.data.username,
            imageUrl: userResponse.data.imageUrl,
          };
        } else {
          console.error('Failed to fetch author details', userResponse.data.msg);
        }

        // 获取文章相关的文件信息
        const fileResponse = await post(`study/static/articleImg/${this.articleId}`);
        if (fileResponse.data.code === 0) {
          this.data.files = fileResponse.data.data;
        } else {
          console.error('Failed to fetch article files', fileResponse.data.msg);
        }
      } else {
        console.error('Failed to fetch article details', articleResponse.data.msg);
      }
    } catch (error) {
      console.error('Error during requests', error);
    }
  },
};
</script>

<style scoped>
.card__comment-item {
  display: flex;
  align-items: flex-start; /* 上对齐 */
  margin-bottom: 16px; /* 调整评论项之间的间距 */
}

.comment-info {
  flex-shrink: 0; /* 防止评论内容挤压头像和名字 */
  margin-right: 12px; /* 调整头像和名字与评论内容的间距 */
}

.card__avatar {
  width: 40px; /* 调整头像大小 */
  height: 40px;
  border-radius: 50%; /* 圆形头像 */
}

.author-name {
  font-weight: bold; /* 加粗显示作者名字 */
  margin-right: 8px; /* 调整头像和名字之间的间距 */
}

.card__comment-content {
  flex: 1; /* 评论内容占据剩余空间 */
  margin: 0; /* 去除默认的段落边距 */
}

/* styles.css 或 main.css */
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.card {
  width: 100%;
  max-width: 400px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 20px;
  margin-top: 20px;
}

.card__title {
  font-size: 1.5em;
  margin-bottom: 10px;
}

.card__author {
  font-style: italic;
  color: #999;
  margin-bottom: 10px;
}
.card__avatar {
  width: 50px; /* 根据需要设置合适的宽度和高度 */
  height: 50px;
  border-radius: 50%; /* 将边框半径设置为50%，即变为圆形 */
  object-fit: cover; /* 确保图片铺满整个圆形区域 */
}

.card__date {
  color: #999;
  margin-bottom: 10px;
}

.card__content {
  text-align: justify;
  line-height: 1.5;
  margin-bottom: 20px;
}

.card__count {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
}

.card__count span {
  font-weight: bold;
}

@media screen and (max-width: 768px) {
  .container {
    padding: 0 10px;
  }


}
</style>